package com.mrx.xfriendship.service;

import com.mrx.commons.exception.BusinessException;
import com.mrx.commons.service.IRateLimiterService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Mr.X
 * @since 2023-02-12 19:24
 */
@Service
@DubboService
public class RateLimiterServiceImpl implements IRateLimiterService {

    private static final Integer RATE_TIME_OUT = 60;

    @Resource
    private IRedisService redisService;

    @Override
    public long tryAcquire(String ip, @Nullable Integer timeout) {
        Boolean exists = redisService.setRateLimiter(ip, timeout == null ? RATE_TIME_OUT : timeout);
        return !exists ? redisService.getRateLimiter(ip).orElse(SUCCEED_LOCKED) : SUCCEED_LOCKED;
    }

    @Override
    public void tryAcquire(String ip) throws BusinessException {
        tryAcquire(ip, null);
    }

}
